package com.kaishengit.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaishengit.entity.Message;

public class Myservlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String state=request.getParameter("state");
		
		if("login".equals(state)){
			login(request,response);
		}else if("context".equals(state)){
			show(request,response);
		}else{
			response.sendError(404);
		}
		
	}

	@SuppressWarnings("unchecked")
	private void show(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException{

		String neirong=request.getParameter("context");
		ServletContext msgApp=getServletContext();
		
		List<Message> lists=(List<Message>) msgApp.getAttribute("neirong");
		if(lists==null){
			lists=new ArrayList<Message>();
		}
		Message msg=new Message();
		msg.setContext(neirong);
		msg.setUsername((String)request.getSession().getAttribute("nicheng"));
		msg.setTime(new SimpleDateFormat("yy-mm-dd HH:mm:ss").format(new Date()));
		lists.add(msg);
		
		msgApp.setAttribute("neirong", lists);
		response.sendRedirect("left-right.jsp");
	}

	@SuppressWarnings("unchecked")
	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException {

		String name=request.getParameter("nicheng");
		request.getSession().setAttribute("nicheng", name);
		
		ServletContext application=request.getSession().getServletContext();
		List<String> lists=(List<String>) application.getAttribute("nameList");
		if(lists==null){
			lists=new ArrayList<String>();
		}
		lists.add(name);
		application.setAttribute("nameList",lists);
		response.sendRedirect("main.jsp");
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
